/*The MIT License

Copyright (c) <1/27/2011> <erick.difiore>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

package com.d4a5.mapping.google
{
	import com.d4a5.mapping.core.AmfPackage;
	import com.d4a5.mapping.core.IAmfObject;
	import com.d4a5.mapping.core.IHighlightedObject;
	import com.d4a5.mapping.core.ISelectedObject;
	import com.d4a5.mapping.core.MapObjectStateContainer;
	import com.google.maps.MapMouseEvent;
	import com.google.maps.interfaces.IOverlay;
	import com.google.maps.interfaces.IPane;
	import com.google.maps.overlays.OverlayBase;
	import com.google.maps.wrappers.WrappableSprite;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	
	
	
	public class wmgGraphicsLayer implements IwmgLayer
	{
		protected var _pane:IPane;
		
		protected var _highlighted:MapObjectStateContainer;
		protected var _selected:MapObjectStateContainer;
		
		public var mouseWiggle:uint = 2;
		protected var _mouseWiggleData:MouseEvent;
		public var hoverDuration:uint = 30;
		protected var _hoverTimer:Timer;
		
		public var moveToTopOnHighlight:Boolean = true;
		public var moveToTopOnSelect:Boolean = true;
		
		protected var _graphicsProvider:ArrayCollection = new ArrayCollection();
		
		protected var _renderer:wmgRenderer = new wmgRenderer();
		
		protected var _mouseDownPoint:Point;
		
		protected var _name:String;
		
		public function wmgGraphicsLayer()
		{
			
			this._highlighted = new MapObjectStateContainer(MapObjectStateContainer.typeIHighlightedObject);
			this._selected = new MapObjectStateContainer(MapObjectStateContainer.typeISelectedObject);
			
			this._hoverTimer = new Timer( this.hoverDuration , 0 );
			this._hoverTimer.addEventListener(TimerEvent.TIMER,onHoverTimerComplete );
			
			this._mouseWiggleData = new MouseEvent( MouseEvent.MOUSE_MOVE , true , false , 0 , 0  );
			
			this.renderer = new wmgDefaultRenderer();
		}
		
		public function get pane() : IPane {
			return this._pane;
		}
		public function set pane( p:IPane ) : void {
			if( this._pane == null && p != null ){
				this._pane = p;
				
				if( this.highlightedOptions ){
					this.pane.map.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
					this.pane.map.addEventListener(MouseEvent.ROLL_OUT,onMouseRollOut);
				}
				if( this.selectedOptions ){
					this.pane.map.addEventListener(MouseEvent.MOUSE_DOWN,OnMouseDown);
					this.pane.map.addEventListener(MouseEvent.CLICK,onMouseClick);
				}
			}
		}
		
		public function get name() : String{
			return this._name;
		}
		public function set name( n:String ) : void{
			this._name = n;
		}
		
		
		
		public function get graphicsProvider() : ArrayCollection {
			return this._graphicsProvider;
		}
		
		public function  addOverlay(arg0:IOverlay):void {
			this.pane.addOverlay( arg0 );
			
			this._graphicsProvider.addItem( arg0 );
			
			if( arg0 is wmgBaseOverlay ){
				arg0.addEventListener( wmgBaseOverlay.EVENT_HIGHLIGHT_TRUE , onGraphicHighlighted );
				arg0.addEventListener( wmgBaseOverlay.EVENT_SELECT_TRUE , onGraphicSelected );
				arg0.addEventListener( wmgBaseOverlay.EVENT_HIGHLIGHT_FALSE , onGraphicDeHighlighted );
				arg0.addEventListener( wmgBaseOverlay.EVENT_SELECT_FALSE , onGraphicDeSelected );
			}
		}
		
		public function removeOverlay(arg0:IOverlay):void {
			this.pane.removeOverlay( arg0 );
			
			var index:int = this._graphicsProvider.getItemIndex( arg0 );
			if( index >= 0 ){
				this._graphicsProvider.removeItemAt( index ); 
				
				if( arg0 is wmgBaseOverlay ){
					arg0.removeEventListener( wmgBaseOverlay.EVENT_HIGHLIGHT_TRUE , onGraphicHighlighted );
					arg0.removeEventListener( wmgBaseOverlay.EVENT_SELECT_TRUE , onGraphicSelected );
					arg0.removeEventListener( wmgBaseOverlay.EVENT_HIGHLIGHT_FALSE , onGraphicDeHighlighted );
					arg0.removeEventListener( wmgBaseOverlay.EVENT_SELECT_FALSE , onGraphicDeSelected );
				}
			}
		}
		
		public function refresh(arg0:Boolean = false) : void {
			var gp:Array = this._graphicsProvider.toArray();
			var length:int = gp.length;
			
			wmgBaseOverlay.refreshMatrix();
			
			for( var i:int = 0; i < length; i++ ){
				gp[i].positionOverlay(arg0);
			}
		}
		
		public function getAmfPackage( name:String ) : AmfPackage {
			var amfs:Array = new Array();
			var gp:Array = this.graphicsProvider.toArray();
			var numGraphics:int = gp.length;
			for( var i:int = 0; i < numGraphics; i++ ){
				amfs.push( gp[i].amf );
			}
			
			return new AmfPackage( name , amfs , AmfPackage.typeAmfObjectData );
		}
		
		
		public function getOptions( arg0:wmgBaseOverlay ) : Object {
			return this._renderer.getOptions( arg0 );
		}
		
		public function get multihighlight() : Boolean {
			return this._highlighted.allowMultiples;
		}
		public function set multihighlight( m:Boolean ) :  void {
			this._highlighted.allowMultiples = m;
		}
		
		public function get multiselect() : Boolean {
			return this._selected.allowMultiples;
		}
		public function set multiselect( m:Boolean ) :  void {
			this._selected.allowMultiples = m;
		}
		
		public function get renderer() : wmgRenderer {
			return this._renderer;
		}
		public function set renderer( r:wmgRenderer ) :  void {
			this._renderer.innerRenderer = r;
		}
		
		public function get defaultOptions() : Object {
			return this._renderer.defaultOptions;
		}
		public function set defaultOptions( options:Object ) : void {
			this._renderer.defaultOptions = options;
		}
		
		public function get highlightedOptions() : Object {
			return this._renderer.highlightedOptions;
		}
		public function set highlightedOptions( options:Object ) : void {
			this._renderer.highlightedOptions = options;
			
			if( this.pane && this.pane.map ){
				if( options ){
					this.pane.map.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
					this.pane.map.addEventListener(MouseEvent.ROLL_OUT,onMouseRollOut);
				}
				else{
					this.pane.map.removeEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
					this.pane.map.removeEventListener(MouseEvent.ROLL_OUT,onMouseRollOut);
				}
			}
		}
		
		public function get selectedOptions() : Object {
			return this._renderer.selectedOptions;
		}
		public function set selectedOptions( options:Object ) : void {
			this._renderer.selectedOptions = options;
			
			if( this.pane && this.pane.map ){
				if( options ){
					this.pane.map.addEventListener(MouseEvent.MOUSE_DOWN,OnMouseDown);
					this.pane.map.addEventListener(MouseEvent.CLICK,onMouseClick);
				}
				else{
					this.pane.map.removeEventListener(MouseEvent.MOUSE_DOWN,OnMouseDown);
					this.pane.map.removeEventListener(MouseEvent.CLICK,onMouseClick);
				}
			}
		}
		
		public function get bothOptions() : Object {
			return this._renderer.bothOptions;
		}
		public function set bothOptions( options:Object ) : void {
			this._renderer.bothOptions = options;
		}
		
		
		protected function onGraphicHighlighted( event:Event ) : void {
			this._highlighted.addItem( event.target );
			
			if( this.moveToTopOnHighlight ){
				this.moveInStack( event.target as wmgBaseOverlay );
			}
		}
		
		protected function onGraphicSelected( event:Event ) : void {
			this._selected.addItem( event.target );
			
			if( this.moveToTopOnSelect ){
				this.moveInStack( event.target as wmgBaseOverlay );
			}
		}
		
		protected function onGraphicDeHighlighted( event:Event ) : void {
			this._highlighted.removeItem( event.target );
			
			if( this.moveToTopOnHighlight ){
				this.moveInStack( event.target as wmgBaseOverlay );
			}
		}
		
		protected function onGraphicDeSelected( event:Event ) : void {
			this._selected.removeItem( event.target );
			
			if( this.moveToTopOnHighlight ){
				this.moveInStack( event.target as wmgBaseOverlay  );
			}
		}
		
		
		public function moveInStack( g:wmgBaseOverlay ) : void {
			var i:int;
			var length:uint;
			var current:wmgBaseOverlay;
			
			length = this._highlighted.length;
			for( i = 0; i < length; i++ ){
				current = this._highlighted[i];
				this.pane.bringToTop( current as IOverlay );
			}
			if( g.highlighted && g != current ){
				this.pane.bringToTop( g as IOverlay );
			}
			
			
			length = this._selected.length
			for( i = 0; i < length; i++ ){
				current = this._selected[i];
				this.pane.bringToTop( current as IOverlay );
			}
			
			if( g.selected && g != current ){
				this.pane.bringToTop( g as IOverlay );
			}
		}
		
		public function get highlighted() : MapObjectStateContainer {
			return this._highlighted;
		}
		public function get selected() : MapObjectStateContainer {
			return this._selected;
		}
		
		protected function onHoverTimerComplete( event:TimerEvent ) : void {
			this._hoverTimer.stop();
			this.highlightGraphicsUnderPt( this._mouseWiggleData );
		}
		
		protected function onMouseMove( event:MouseEvent ) : void {
			if( event.target is OverlayBase ){
				var currentPt:Point = new Point( event.stageX , event.stageY );
				
				var doSomething:Boolean = ( this.mouseWiggle == 0 || this.mouseWiggle < Point.distance( currentPt , new Point( this._mouseWiggleData.stageX , this._mouseWiggleData.stageY ) ) );
				
				if( doSomething ){
					this._mouseWiggleData = event;
					
					if( this.hoverDuration == 0 ){
						this.highlightGraphicsUnderPt( this._mouseWiggleData );
					}
					else{
						this._hoverTimer.stop();
						this._hoverTimer.delay = this.hoverDuration;
						this._hoverTimer.start();
					}
				}
			}
			else{
				this._highlighted.removeAll();
			}
		}
		
		protected function highlightGraphicsUnderPt( ptData:MouseEvent ) : void {
			var gp:Array = this.graphicsProvider.toArray();
			var gpLength:int = gp.length;
			var h:Object;
			
			
			if( ptData.stageX == 0 && ptData.stageY == 0 ){
				this._highlighted.removeAll();
				return;
			}
			
			
			if( this.multihighlight ){
				for( var j:int = 0; j < gpLength; j++ ){
					h = gp[j];
					
					if( h is IHighlightedObject ){
						h.highlighted = h.hitTestPoint( ptData.stageX , ptData.stageY , true );
					}
				}
			}
			else{
				var nearest:Object = {distSqr:Number.MAX_VALUE, graphic:null};
				var m:Matrix;
				
				for( var i:int = 0; i < gpLength; i++ ){
					h = gp[i];
					if( h is wmgBaseOverlay ){
						
						if( h.hitTestPoint( ptData.stageX , ptData.stageY , true ) ){
							m = ( m ) ? m : h.getMatrix();
							
							var center:Point = (h as wmgBaseOverlay).amf.bounds.center;
							var cX:Number = (m.a * center.x) + m.tx ;
							var cY:Number = (m.b * center.y) + m.ty ;
							var distSqr:Number = (cX - ptData.localX)*(cX - ptData.localX) + (cY - ptData.localY)*(cY - ptData.localY);
							
							if( distSqr < nearest.distSqr ){
								if( nearest.graphic ){
									nearest.graphic.highlighted = false;
								}
								nearest.graphic = h;
								nearest.distSqr = distSqr;
							}
							else{
								h.highlighted = false;
							}
						}
						else{
							h.highlighted = false;
						}
					}
				}
				
				if( nearest.graphic ){
					nearest.graphic.highlighted = true;
				}
			}
		}
		
		
		
		protected function onMouseRollOut( event:MouseEvent ) : void {
			this._hoverTimer.stop();
			this._highlighted.removeAll();
		}
		
		protected function OnMouseDown( event:MouseEvent ) : void {
			this._mouseDownPoint = new Point( event.stageX , event.stageY );
		}
		
		protected function onMouseClick( event:MouseEvent ) : void {
			if( Point.distance( this._mouseDownPoint , new Point( event.stageX , event.stageY ) ) < this.mouseWiggle ){
				if( event.target is OverlayBase ){
					this.selectGraphicsUnderPt( event );
				}
				else{
					this.selected.removeAll();
				}
			}
			
		}
		
		protected function selectGraphicsUnderPt( ptData:MouseEvent ) : void {
			var gp:Array = this.graphicsProvider.toArray();
			var gpLength:int = gp.length;
			var s:Object;
			
			if( this.multiselect ){
				for( var j:int = 0; j < gpLength; j++ ){
					s = gp[j];
					if( s is ISelectedObject ){
						s.selected = ( s.hitTestPoint( ptData.stageX , ptData.stageY , true ) )
							? (( s.selected )
								? false : true)
							: (( s.selected )
								? true : false);
					}
				}
			}
			else{
				var nearest:Object = {distSqr:Number.MAX_VALUE, graphic:null};
				var m:Matrix;
				
				for( var i:int = 0; i < gpLength; i++ ){
					s = gp[i];
					if( s is wmgBaseOverlay ){
						
						if( s.hitTestPoint( ptData.stageX , ptData.stageY , true ) ){
							m = ( m ) ? m : s.getMatrix();
							
							var center:Point = (s as wmgBaseOverlay).amf.bounds.center;
							var cX:Number = (m.a * center.x) + m.tx ;
							var cY:Number = (m.b * center.y) + m.ty ;
							var distSqr:Number = (cX - ptData.localX)*(cX - ptData.localX) + (cY - ptData.localY)*(cY - ptData.localY);
							
							if( distSqr < nearest.distSqr ){
								if( nearest.graphic ){
									nearest.graphic.selected = false;
								}
								nearest.graphic = s;
								nearest.distSqr = distSqr;
							}
							else{
								s.selected = false;
							}
						}
						else{
							s.selected = false;
						}
					}
				}
				
				if( nearest.graphic ){
					nearest.graphic.selected = true;
				}
			}
		}
	}
}